package com.ocom.emqx.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.ocom.common.entity.emqx.*;
import com.ocom.common.entity.mongo.EntityDeviceHistoryPo;
import com.ocom.common.entity.payconfig.EntityMqttDevice;
import com.ocom.common.request.emqx.*;
import com.ocom.common.resp.Result;
import com.ocom.common.vo.emqx.YhDeviceWorkStatusVo;
import com.ocom.common.vo.emqx.YhStatusVo;
import com.ocom.emqx.client.PayconfigFeignService;
import com.ocom.emqx.client.XfRecodeFeignService;
import com.ocom.emqx.handle.MqttSendClient;
import com.ocom.emqx.service.WashingMachineService;
import com.ocom.emqx.util.DesUtils;
import com.ocom.emqx.util.EmqxApiUtil;
import com.ocom.emqx.util.EmqxConvert;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


@Slf4j
@Service
public class WashingMachineServiceImpl implements WashingMachineService {

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    PayconfigFeignService payconfigFeignService;


    @Autowired
    MqttSendClient mqttSendClient;

    @Autowired
    private XfRecodeFeignService xfRecodeFeignService;

    //84协议
//    @Override
//    public void updateMachIneStatusWd(String deviceNo , String msg){
//        //解密参数
//        String org = checkMsg(msg);
//
//
////        if(org.startsWith("000100000001")){
////            Result<EntityMqttDevice> result = payconfigFeignService.getMqttDeviceInfo(deviceNo);
////            if(result.getCode()!=200){
////                log.info("mqtt设备未注册1 【{}】",deviceNo);
////                return;
////            }
////            redisUtil.hmSet("MqttXfDevice:" + deviceNo, "deviceStatus",result.getData().getDeviceStatus());
////            redisUtil.hmSet("MqttXfDevice:" + deviceNo, "errStatus",result.getData().getErrStatus());
////            redisUtil.hmSet("MqttXfDevice:" + deviceNo, "comId",result.getData().getComId());
////
////            // 创建一个Random类的实例
////            Random random = new Random();
////            // 生成一个随机整数
////            Integer randomIntBound = random.nextInt(3000);
////
////            redisUtil.expire("MqttXfDevice:" + deviceNo , 7200l+randomIntBound);
////
////            mqttSendClient.publish(false,  "ws/cm/"+deviceNo , EmqxApiUtil.washing03(deviceNo,result.getData().getComId()) );
////        }
//
//        //00520000000101020600000000
//        Integer deviceStatus = Integer.valueOf(org.substring(14,16));
//        Integer errStatus = Integer.valueOf(org.substring(16,18));
//
//        Integer deviceStatusOldInt = 0;
//        Integer errStatusOldInt = 0;
//
//        Object deviceStatusOld  =  redisUtil.hmGet("MqttXfDevice:" + deviceNo, "deviceStatus");
//        Object errStatusOld  =  redisUtil.hmGet("MqttXfDevice:" + deviceNo, "errStatus");
//
//        if (deviceStatusOld == null || errStatusOld == null) {
//            Result<EntityMqttDevice> result = payconfigFeignService.getMqttDeviceInfo(deviceNo);
//            if(result.getCode()!=200){
//                log.info("mqtt设备未注册2 【{}】",deviceNo);
//                return;
//            }
//            redisUtil.hmSet("MqttXfDevice:" + deviceNo, "deviceStatus",result.getData().getDeviceStatus());
//            redisUtil.hmSet("MqttXfDevice:" + deviceNo, "errStatus",result.getData().getErrStatus());
//            redisUtil.hmSet("MqttXfDevice:" + deviceNo, "comId",result.getData().getComId());
//
//            // 创建一个Random类的实例
//            Random random = new Random();
//            // 生成一个随机整数
//            Integer randomIntBound = random.nextInt(3000);
//
//            redisUtil.expire("MqttXfDevice:" + deviceNo , 7200l+randomIntBound);
//
//            EntityMqttDevice entityMqttDevice =new EntityMqttDevice();
//            entityMqttDevice.setMqttDeviceNo(deviceNo);
//            entityMqttDevice.setComId( result.getData().getComId());
//            entityMqttDevice.setOnline(true);
//            entityMqttDevice.setCommTime(new Date());
//            this.updateDeviceStatus(entityMqttDevice);
//
//        }else{
//            deviceStatusOldInt = (Integer) deviceStatusOld;
//            errStatusOldInt = (Integer) errStatusOld;
//        }
//
//        //更新状态
//        if(deviceStatus!=deviceStatusOldInt || errStatus!=errStatusOldInt){
//            redisUtil.hmSet("MqttXfDevice:" + deviceNo, "deviceStatus",deviceStatus);
//            redisUtil.hmSet("MqttXfDevice:" + deviceNo, "errStatus",errStatus);
//
//            // 创建一个Random类的实例
//            Random random = new Random();
//            // 生成一个随机整数
//            Integer randomIntBound = random.nextInt(3000);
//
//            redisUtil.expire("MqttXfDevice:" + deviceNo , 7200l+randomIntBound);
//
//            EntityMqttDevice entityMqttDevice =new EntityMqttDevice();
//            entityMqttDevice.setMqttDeviceNo(deviceNo);
//            entityMqttDevice.setComId( ((Integer)redisUtil.hmGet("MqttXfDevice:" + deviceNo, "comId")).longValue());
//            entityMqttDevice.setDeviceStatus(deviceStatus);
//            entityMqttDevice.setErrStatus(errStatus);
//            entityMqttDevice.setOnline(true);
//            entityMqttDevice.setCommTime(new Date());
//            this.updateDeviceStatus(entityMqttDevice);
//        }
//        return;
//    }

    //84协议重写
    @Override
    public void updateMachIneStatusWd(String deviceNo, String msg) {
        EntityYhMqtt84 entityYhMqtt84 = EmqxConvert.convertYhMqtt84(msg);
        log.info("接收到84数据包：【{}】，设备号:【{}】，：拆包后的数据：【{}】",msg,deviceNo,JSON.toJSONString(entityYhMqtt84));
        EntityDeviceHistoryPo deviceHistoryPo = Convert.convert(EntityDeviceHistoryPo.class,entityYhMqtt84);
        deviceHistoryPo.setDeviceNo(deviceNo);
        deviceHistoryPo.setCommandType("84");
//        this.addHistoryRecord(deviceHistoryPo);
        EntityMqttDevice entityMqttDevice = this.getDevice(deviceNo,entityYhMqtt84.getSubString());
        this.updateDeviceStatus(entityMqttDevice,deviceHistoryPo);
//        boolean bUpdate = true;
//        if(!entityYhMqtt84.getStatus().equals(entityMqttDevice.getDeviceStatus()) || !entityYhMqtt84.getErrorStatus().equals(entityMqttDevice.getErrStatus()) || !entityMqttDevice.getOrderStatus().equals(0)){
//            //TODO  更新状态信息
//
//            bUpdate = true;
//        }
//
//        YhStatusVo yhStatus = this.yHStatus(entityYhMqtt84.getStatus(),entityMqttDevice.getDeviceStatus());
//        log.info("log_1:当前设备：【{}】，工作状态是：【{}】，当前设备参数：【{}】",deviceNo,JSON.toJSONString(yhStatus),JSON.toJSONString(entityMqttDevice));
//
//        //无变更
//        if(!Lists.newArrayList(0,1,2).contains(yhStatus.getNewSub())){
////            this.updateDeviceInfo(deviceNo, entityMqttDevice.getComId(), entityYhMqtt84.getStatus(),entityYhMqtt84.getErrorStatus(),entityMqttDevice.getOrderStatus(),entityMqttDevice.getSubRun());
//            log.info("log_2：无变更");
//        }
//
//        //洗衣机变更
//        if(yhStatus.getNewSub().equals(0)){
//            if(entityMqttDevice.getOrderStatus().equals(2) && yhStatus.getNewState0() > 0){
//                //TODO 设备开始工作
//                this.deviceStartWork(entityMqttDevice,yhStatus);
//                this.updateDeviceCommand(deviceNo,"_run_8A",0);
//                log.info("log_3:洗衣机开始工作：设备号：【{}】",deviceNo);
//            }
//
//            if(entityMqttDevice.getDeviceStatus().equals(0) && yhStatus.getNewState0().equals(0)){
//                //TODO 设备停止工作
//                this.deviceStopWork(entityMqttDevice,yhStatus);
//                log.info("log_4:洗衣机停止工作：设备号：【{}】",deviceNo);
//            }
////            this.updateDeviceInfo(deviceNo, entityMqttDevice.getComId(), entityYhMqtt84.getStatus(),entityYhMqtt84.getErrorStatus(),entityMqttDevice.getOrderStatus(),entityMqttDevice.getSubRun());
//        }
//
////      一控二变更
//        if(Lists.newArrayList(0,1).contains(entityMqttDevice.getOrderStatus())){
//            if((yhStatus.getNewSub().equals(1) && yhStatus.getNewState1().equals(0)) || (yhStatus.getNewSub().equals(2) && yhStatus.getNewState2().equals(0))){
////              设备停止工作
//                this.deviceStopWork(entityMqttDevice,yhStatus);
//                log.info("log_5,吹风机停止工作：设备号：【{}】",deviceNo);
//            }
////            this.updateDeviceInfo(deviceNo, entityMqttDevice.getComId(), entityYhMqtt84.getStatus(),entityYhMqtt84.getErrorStatus(),entityMqttDevice.getOrderStatus(),entityMqttDevice.getSubRun());
//
//        }
//
//        if(Lists.newArrayList(2).contains(entityMqttDevice.getOrderStatus())){
////        （有新订单）
//            if(yhStatus.getOrdered().equals(1)){
//                if((yhStatus.getNewSub().equals(1) && yhStatus.getNewState1().equals(0)) || (yhStatus.getNewSub().equals(2) && yhStatus.getNewState2().equals(0))){
////              设备停止工作
//                    this.deviceStopWork(entityMqttDevice,yhStatus);
//                    log.info("log_6,吹风机停止工作：有新订单：设备号：【{}】",deviceNo);
//                }
////                this.updateDeviceInfo(deviceNo, entityMqttDevice.getComId(), entityYhMqtt84.getStatus(),entityYhMqtt84.getErrorStatus(),entityMqttDevice.getOrderStatus(),entityMqttDevice.getSubRun());
//            }
//
//            if(yhStatus.getOrdered().equals(0)){
//                if((yhStatus.getNewSub().equals(1) && yhStatus.getNewState1().equals(0)) || (yhStatus.getNewSub().equals(2) && yhStatus.getNewState2().equals(0))){
//                    this.deviceStopWork(entityMqttDevice,yhStatus);
//                    log.info("log_7,吹风机停止工作：无新订单或新订单开始：设备号：【{}】",deviceNo);
//                }
//
//                //左路开始工作
//                if(yhStatus.getNewSub().equals(1) && yhStatus.getNewState1() > 0){
//                    this.deviceStartWork(entityMqttDevice, yhStatus);
//                    log.info("log_7,吹风机开始工作：左路开始工作：设备号：【{}】",deviceNo);
//                    this.updateDeviceCommand(deviceNo,"_run_8A",1);
//                }
//
//                //右路开始工作
//                if(yhStatus.getNewSub().equals(2) && yhStatus.getNewState2() > 0){
//                    this.deviceStartWork(entityMqttDevice,yhStatus);
//                    log.info("log_7,吹风机开始工作：右路开始工作：设备号：【{}】",deviceNo);
//                    this.updateDeviceCommand(deviceNo,"_run_8A",2);
//                }
//            }
//        }
//        Integer resultSub = Integer.valueOf(redisUtil.hmGet("MqttXfDevice:"+ entityMqttDevice.getMqttDeviceNo(),"subRun").toString());
//        if(ObjectUtil.isNotEmpty(resultSub)){
//            entityMqttDevice.setSubRun(resultSub);
//        }
//        if(bUpdate){
//            log.info("84更新设备状态：【{}】【{}】【{}】【{}】【{}】",deviceNo,JSON.toJSONString(entityYhMqtt84),JSON.toJSONString(entityMqttDevice),JSON.toJSONString(entityYhMqtt84),resultSub);
//            this.updateDeviceInfo(deviceNo, entityMqttDevice.getComId(), entityYhMqtt84.getStatus(),entityYhMqtt84.getErrorStatus(),yhStatus.getOrdered(),entityMqttDevice.getSubRun());
//        }
//        log.info("log_7:84结束");
    }

    @Override
    public EntityMqttDevice getDevice(String deviceNo,String subString) {

        EntityMqttDevice entityMqttDevice;
        String MqttDeviceNo = (String) redisUtil.hmGet("MqttXfDevice:"+ deviceNo,"mqtt_device_no");
        Integer mqttDeviceId =  (Integer) redisUtil.hmGet("MqttXfDevice:"+ deviceNo,"mqttDeviceId");
        if(ObjectUtil.isEmpty(MqttDeviceNo) || ObjectUtil.isEmpty(mqttDeviceId)){
            Result<EntityMqttDevice> result = payconfigFeignService.getMqttDeviceInfo(deviceNo);
            if(result.getCode() != 200){
                log.info("mqtt设备为未注册1【{}】",deviceNo);
                return null;
            }
            entityMqttDevice = result.getData();
            redisUtil.hmSet("MqttXfDevice:"+ deviceNo,"mqttDeviceNo",entityMqttDevice.getMqttDeviceNo());
            redisUtil.hmSet("MqttXfDevice:"+ deviceNo,"orderStatus",entityMqttDevice.getOrderStatus());
            redisUtil.hmSet("MqttXfDevice:"+ deviceNo,"mqttDeviceName",entityMqttDevice.getMqttDeviceName());
            redisUtil.hmSet("MqttXfDevice:"+ deviceNo,"subRun",entityMqttDevice.getSubRun());
            redisUtil.hmSet("MqttXfDevice:"+ deviceNo,"subNum",entityMqttDevice.getSubNum());
            redisUtil.hmSet("MqttXfDevice:"+ deviceNo,"comId",entityMqttDevice.getComId());
            redisUtil.hmSet("MqttXfDevice:" + deviceNo, "deviceStatus",entityMqttDevice.getDeviceStatus());
            redisUtil.hmSet("MqttXfDevice:" + deviceNo, "errStatus",entityMqttDevice.getErrStatus());
            redisUtil.hmSet("MqttXfDevice:" + deviceNo, "mqttDeviceId",entityMqttDevice.getMqttDeviceId());

        }else{
            entityMqttDevice = new EntityMqttDevice();
            entityMqttDevice.setMqttDeviceNo(MqttDeviceNo);
            Integer subRun = (Integer) redisUtil.hmGet("MqttXfDevice:"+ deviceNo,"subRun");
            Integer subNum =(Integer) redisUtil.hmGet("MqttXfDevice:"+ deviceNo,"subNum");
            entityMqttDevice.setOrderStatus((Integer) redisUtil.hmGet("MqttXfDevice:"+ deviceNo,"orderStatus"));
            entityMqttDevice.setMqttDeviceName((String) redisUtil.hmGet("MqttXfDevice:"+ deviceNo,"mqttDeviceName"));
            entityMqttDevice.setSubRun(ObjectUtil.isEmpty(subRun)?0:subRun);
            entityMqttDevice.setSubNum(ObjectUtil.isEmpty(subNum)?0:subNum);
            Integer comId =  (Integer) redisUtil.hmGet("MqttXfDevice:"+ deviceNo,"comId");
            entityMqttDevice.setComId(comId.longValue());
            entityMqttDevice.setDeviceStatus((Integer) redisUtil.hmGet("MqttXfDevice:"+ deviceNo,"deviceStatus"));
            entityMqttDevice.setErrStatus((Integer) redisUtil.hmGet("MqttXfDevice:"+ deviceNo,"errStatus"));
            entityMqttDevice.setMqttDeviceId(mqttDeviceId.longValue());
        }


        //下发设备标志
//        if(!subString.equals("0xFFFF00000000"+entityMqttDevice.getComId())){
//            mqttSendClient.publish(false,  "ws/cm/"+deviceNo , EmqxApiUtil.washing03(deviceNo,entityMqttDevice.getComId()) );
//        }

        return entityMqttDevice;
    }

    @Override
    public YhDeviceWorkStatusVo yhDeviceWorkStatus(Integer status, Integer subRun, Integer subNum) {
        log.info("收到判断子设备工作状态参数：(yhDeviceWorkStatus)：status：【{}】，subRun：【{}】,subNum：【{}】",status,subRun,subNum);
        status = ObjectUtil.isEmpty(status)?0:status;
        subRun = ObjectUtil.isEmpty(subRun)?0:subRun;
        subNum = ObjectUtil.isEmpty(subNum)?0:subNum;
        YhDeviceWorkStatusVo yhStatus = new YhDeviceWorkStatusVo();
        Map<Integer,Integer> sub  = new HashMap<>();
        for (int i = 0;i<=2;i++){
//            sub.put(i,subRun >> 1);
            int sunRunA = (subRun & (int)Math.pow(2,i)) > 0?1:0;
            sub.put(i,sunRunA);
            yhStatus.setOrdered(0);
        }

        if(Lists.newArrayList(1).contains(status)){
            sub.put(0,1);
        }else if(Lists.newArrayList(21,31).contains(status)){
            sub.put(1,1);
        }else if(Lists.newArrayList(22,32).contains(status)){
            sub.put(2,1);
        }else  if(Lists.newArrayList(23,33).contains(status)){
            sub.put(1,1);
            sub.put(2,1);
        }else if(Lists.newArrayList(34).contains(status)){
            sub.put(1,1);
            yhStatus.setOrdered(1);
        }else if(Lists.newArrayList(35).contains(status)){
            sub.put(2,1);
            yhStatus.setOrdered(1);
        }else if(Lists.newArrayList(30).contains(status)){
            yhStatus.setOrdered(1);
        }

        if((sub.get(0) + sub.get(1) + sub.get(2)) == 0){
            yhStatus.setRunState(0);
            yhStatus.setRunSub(0);
            log.info("判断设备状态,log_1:返回：【{}】",JSON.toJSONString(yhStatus));
            return yhStatus;
        }

        if(sub.get(0) == 1){
            yhStatus.setRunSub(1);
            yhStatus.setRunState(1);
            yhStatus.setOrdered(0);
            log.info("判断设备状态,log_2:返回：【{}】",JSON.toJSONString(yhStatus));
            return yhStatus;
        }

        if((sub.get(1) + sub.get(2)) < subNum){
            yhStatus.setRunState(0);
            yhStatus.setRunSub(sub.get(1) + sub.get(2));
            log.info("判断设备状态,log_3:返回：【{}】",JSON.toJSONString(yhStatus));
            return yhStatus;
        }else{
            yhStatus.setRunState(1);
            yhStatus.setRunSub(sub.get(1) + sub.get(2));
            log.info("判断设备状态,log_4:返回：【{}】",JSON.toJSONString(yhStatus));
            return yhStatus;
        }
    }

    @Override
    public YhStatusVo yHStatus(Integer status, Integer subRun) {
        //
        YhStatusVo yhStatus = new YhStatusVo();
        Map<Integer,Integer> oldsStatus = new HashMap<>();
        for (int i = 0;i<=2;i++){
            oldsStatus.put(i,subRun >> 1);
            yhStatus.setOrdered(0);
            yhStatus.setNewSub(-1);
            yhStatus.setNewState0(0);
            yhStatus.setNewState1(0);
            yhStatus.setNewState2(0);
        }

        if(status.equals(0)){
            if(oldsStatus.get(0).equals(1)){
                yhStatus.setNewSub(0);  //洗衣机空闲
            }

            if(oldsStatus.get(1).equals(1)){
                yhStatus.setNewSub(1);  //左路空闲
            }

            if(oldsStatus.get(2).equals(1)){
                yhStatus.setNewSub(1);   //右路空闲
            }
        }

        //洗衣机工作
        if(status.equals(1)){
            yhStatus.setNewState0(1);
            if(oldsStatus.get(0).equals(0)){
                yhStatus.setNewSub(0);
                return yhStatus;
            }
        }

        //左路工作、右路不工作
        if(Lists.newArrayList(21,31,34).contains(status)){
            yhStatus.setNewState1(1);
        }

        //左路不工作、右路工作
        if(Lists.newArrayList(22,32,35).contains(status)){
            yhStatus.setNewState2(1);
        }

        if(Lists.newArrayList(23,33).contains(status)){
            yhStatus.setNewState1(1);
            yhStatus.setNewState2(1);
        }

        if(Lists.newArrayList(30).contains(status)){
            yhStatus.setNewState1(0);
            yhStatus.setNewState2(0);
        }

        if(Lists.newArrayList(30,34,35).contains(status)){
            yhStatus.setOrdered(1);
        }

        //（左路开始工作）
        if(yhStatus.getNewState1().equals(0) && oldsStatus.get(1).equals(1)){
            yhStatus.setNewSub(1);
        }

        //（右路开始工作）
        if(yhStatus.getNewState2().equals(0) && oldsStatus.get(2).equals(1)){
            yhStatus.setNewSub(2);
        }

        if(yhStatus.getNewState1().equals(1) && oldsStatus.get(1).equals(0)){
            yhStatus.setNewSub(1);
        }

        if(yhStatus.getNewState2().equals(1) && oldsStatus.get(2).equals(0)){
            yhStatus.setNewSub(2);
        }
        return yhStatus;
    }

    @Override
    public EntityMqttDevice getDevice(String deviceNo) {
        return this.getDevice(deviceNo,"");
    }

    @Override
    public void updateMachIneStatusOd(String deviceNo , String msg) {

    }

    @Override
    public void updateDeviceStatus(EntityMqttDevice entityMqttDevice) {
        payconfigFeignService.updateByDeviceNo(entityMqttDevice);
    }

    //86
    @Override
    public void comfirmOrder(String deviceNo , String msg) {
        log.info("86命令接收到的数据，设备号：【{}】，数据包：【{}】",deviceNo,msg);
        EntityYhMqtt86 entityYhMqtt86 = EmqxConvert.convertYhMqtt86(msg);
        log.info("解析86数据包得到的数据：{}",JSON.toJSONString(entityYhMqtt86));
        if(entityYhMqtt86.getStatus().equals(0)){
            //成功
            YhMqtt07Request yhMqtt07Request = new YhMqtt07Request();
            yhMqtt07Request.setOrderNo(entityYhMqtt86.getOrderNo());
            yhMqtt07Request.setRandomCode(entityYhMqtt86.getRandomCode());
            EntityYhMqtt07 entityYhMqtt07 = EmqxConvert.convertYhMqtt07(yhMqtt07Request);
            this.publish(deviceNo,entityYhMqtt07.getEncryptionCommand());

            log.info("07发出的数据：{}",JSON.toJSONString(entityYhMqtt07));
            this.updateDeviceCommand(deviceNo,"_"+entityYhMqtt86.getOrderNo()+"_86",1);
//            redisUtil.set("MqttOrder:" + deviceNo +":"+entityYhMqtt86.getOrderNo(), 1 , 30L);
        }else{
            //失败
//            redisUtil.set("MqttOrder:" + deviceNo +":"+entityYhMqtt86.getOrderNo(), 0 , 30L);
            this.updateDeviceCommand(deviceNo,"_"+entityYhMqtt86.getOrderNo()+"_86",0);
        }
    }

    //87
    @Override
    public void comfirmOrderTwo(String deviceNo , String msg) {

        EntityYhMqtt87 entityYhMqtt87 = EmqxConvert.convertYhMqtt87(msg);
        log.info("收到87的数据：设备号：【{}】，数据包：【{}】，解析后的数据：【{}】",deviceNo,msg,JSON.toJSONString(entityYhMqtt87));
        this.updateDeviceCommand(deviceNo,"_"+entityYhMqtt87.getOrderNo()+"_87",entityYhMqtt87.getStatus());
    }

    @Override
    public EntityYhMqtt0607 yHMqtt0607(YhMqtt0607Request request) {
        log.info("yhMqtt0607参数：【{}】", JSON.toJSONString(request));
        EntityYhMqtt0607 entityYhMqtt0607 = EmqxConvert.convertYhMqtt0607(request);
        log.info("yhMqtt0607转化后的参数：【{}】", JSON.toJSONString(entityYhMqtt0607));
        this.publish(request.getDeviceNo(),entityYhMqtt0607.getEncryptionCommand(), entityYhMqtt0607.getOrderNo());
        return entityYhMqtt0607;
    }

    @Override
    public EntityYhMqtt0606 yHMqtt0606(YhMqtt0606Request request) {
        log.info("yhMqtt0606参数：【{}】", JSON.toJSONString(request));
        EntityYhMqtt0606 entityYhMqtt0606 = EmqxConvert.convertYhMqtt0606(request);
        log.info("yhMqtt0606转化后的参数：【{}】", JSON.toJSONString(entityYhMqtt0606));
        this.publish(request.getDeviceNo(),entityYhMqtt0606.getEncryptionCommand(), entityYhMqtt0606.getOrderNo());
        return entityYhMqtt0606;
    }

    @Override
    public void publish(String deviceNo, String pushMessage,Long orderId) {
        mqttSendClient.publish(false,  "ws/cm/"+deviceNo , pushMessage);
    }

    @Override
    public void publish(String deviceNo, String pushMessage) {
        this.mqttSendClient.publish(false,"ws/cm/"+deviceNo,pushMessage);
    }

    @Override
    public void yHMqtt8A(String deviceNo, String msg) {

        String redisKey = "MqttXfDevice:" + deviceNo;
        Integer deviceStatus = (Integer)redisUtil.hmGet(redisKey,"deviceStatus");
        Integer errStatus = (Integer)redisUtil.hmGet(redisKey,"errStatus");


        EntityYhMqtt8A entityYhMqtt8A = EmqxConvert.convertYhMqtt8A(msg);
        EntityMqttDevice entityMqttDevice =new EntityMqttDevice();
        entityMqttDevice.setMqttDeviceNo(deviceNo);
        entityMqttDevice.setDeviceStatus(entityYhMqtt8A.getStatus());
        entityMqttDevice.setErrStatus(entityYhMqtt8A.getErrorStatus());
        log.info("yHMqtt8A参数：设备号【{}】，数据包：【{}】，解析后的数据：【{}】", deviceNo,msg,JSON.toJSONString(entityYhMqtt8A));
        //TODO
        EntityDeviceHistoryPo deviceHistoryPo = Convert.convert(EntityDeviceHistoryPo.class,entityYhMqtt8A);
        deviceHistoryPo.setDeviceNo(deviceNo);
        deviceHistoryPo.setCommandType("8A");
        EntityMqttDevice entityMqttDeviceA = getDevice(deviceNo,"");
        this.updateDeviceStatus(entityMqttDeviceA,deviceHistoryPo);
//        this.addHistoryRecord(deviceHistoryPo);
//

//        YhStatusVo yhStatusVo = this.yHStatus(entityYhMqtt8A.getStatus(),entityMqttDeviceA.getSubRun());
//        if(entityMqttDeviceA.getOrderStatus().equals(2) && yhStatusVo.getNewState0() > 0){
//            this.updateDeviceCommand(deviceNo,"_run_8A",0);
//        }
//
//        if(entityYhMqtt8A.getStatus().equals(deviceStatus) && entityYhMqtt8A.getErrorStatus().equals(errStatus)  ){
//            return;
//        }
//
////        Result<EntityMqttDevice> result = payconfigFeignService.getMqttDeviceInfo(deviceNo);
////        if(result.getCode()!=200){
////            log.info("mqtt设备未注册2 【{}】",deviceNo);
////            return;
////        }
////        EntityMqttDevice entityMqttDeviceA = this.getDevice(deviceNo);
//        entityMqttDevice.setComId(entityMqttDeviceA.getComId());
//
//        this.updateDeviceStatus(entityMqttDevice);
        redisUtil.hmSet("MqttXfDevice:" + deviceNo, "stopTime", DateUtil.offset(new Date(), DateField.SECOND,entityYhMqtt8A.getRemainderTime()).getTime());



    }

    private void updateDeviceInfo(String deviceNo,Long comId,Integer deviceStatus,Integer errStatus,Integer orderStatus,Integer subRun){
        EntityMqttDevice entityMqttDevice = new EntityMqttDevice();
        entityMqttDevice.setDeviceStatus(deviceStatus);
        entityMqttDevice.setErrStatus(errStatus);
        entityMqttDevice.setComId(comId);
        entityMqttDevice.setMqttDeviceNo(deviceNo);
        entityMqttDevice.setOrderStatus(orderStatus);
        entityMqttDevice.setSubRun(subRun);
        this.updateDeviceStatus(entityMqttDevice);
        log.info("更新设备状态：【{}】，设备号：【{}】",JSON.toJSONString(entityMqttDevice),deviceNo);

        redisUtil.hmSet("MqttXfDevice:"+ deviceNo,"orderStatus",entityMqttDevice.getOrderStatus());
        redisUtil.hmSet("MqttXfDevice:"+ deviceNo,"subRun",entityMqttDevice.getSubRun());
        redisUtil.hmSet("MqttXfDevice:" + deviceNo, "deviceStatus",entityMqttDevice.getDeviceStatus());
        redisUtil.hmSet("MqttXfDevice:" + deviceNo, "errStatus",entityMqttDevice.getErrStatus());
    }

    @Override
    public void updateDeviceCommand(String deviceNo,String deviceKey,Object value){
        this.redisUtil.set("YH_"+deviceNo+deviceKey,value,10L);
    }

    //设备开始工作
    private void deviceStartWork(EntityMqttDevice entityMqttDevice,YhStatusVo yhStatus){

        DeviceStartWorkRequest request = new DeviceStartWorkRequest();
        request.setMqttDeviceId(entityMqttDevice.getMqttDeviceId());
        request.setComId(entityMqttDevice.getComId());
        request.setSubRun(entityMqttDevice.getSubRun());
        request.setMqttDeviceNo(entityMqttDevice.getMqttDeviceNo());
        request.setOrderId(entityMqttDevice.getOrderId());
        request.setState(31);
        request.setMqttDeviceSub(yhStatus.getNewSub());
        log.info("设备开始工作:参数【{}】",JSON.toJSONString(request));
        this.payconfigFeignService.deviceStartWork(request);
    }

    //设备停止工作
    private void  deviceStopWork(EntityMqttDevice entityMqttDevice,YhStatusVo yhStatus){
        DeviceStopWorkRequest request = new DeviceStopWorkRequest();
        request.setComId(entityMqttDevice.getComId());
        request.setMqttDeviceId(entityMqttDevice.getMqttDeviceId());
        request.setMqttDeviceNo(entityMqttDevice.getMqttDeviceNo());
        request.setMqttDeviceSub(entityMqttDevice.getSubRun());
        request.setNewSub(yhStatus.getNewSub());
        request.setSubRun(yhStatus.getNewSub());
        this.payconfigFeignService.deviceStopWork(request);
        log.info("设备结束工作:参数【{}】",JSON.toJSONString(request));
    }

    @Override
    public void addHistoryRecord(EntityDeviceHistoryPo deviceHistoryPo) {
        this.xfRecodeFeignService.saveDeviceHistory(deviceHistoryPo);
    }

    @Override
    public void updateDeviceStatus(EntityMqttDevice entityMqttDevice, EntityDeviceHistoryPo deviceHistoryPo) {
        this.addHistoryRecord(deviceHistoryPo);
//        EntityMqttDevice entityMqttDevice = this.getDevice(deviceHistoryPo.getDeviceNo(),deviceHistoryPo.getSubString());
        boolean bUpdate = true;
//        if(!deviceHistoryPo.getStatus().equals(entityMqttDevice.getDeviceStatus()) || !deviceHistoryPo.getErrorStatus().equals(entityMqttDevice.getErrStatus()) || !entityMqttDevice.getOrderStatus().equals(0)){
//            //TODO  更新状态信息
//
//            bUpdate = true;
//        }

        YhStatusVo yhStatus = this.yHStatus(deviceHistoryPo.getStatus(),entityMqttDevice.getSubRun());
        log.info("log_1:当前设备：【{}】，工作状态是：【{}】，当前设备参数：【{}】",deviceHistoryPo.getDeviceNo(),JSON.toJSONString(yhStatus),JSON.toJSONString(entityMqttDevice));

        //无变更
        if(!Lists.newArrayList(0,1,2).contains(yhStatus.getNewSub())){
//            this.updateDeviceInfo(deviceNo, entityMqttDevice.getComId(), entityYhMqtt84.getStatus(),entityYhMqtt84.getErrorStatus(),entityMqttDevice.getOrderStatus(),entityMqttDevice.getSubRun());
            log.info("log_2：无变更");
        }

        //洗衣机变更
        if(yhStatus.getNewSub().equals(0)){
            if(entityMqttDevice.getOrderStatus().equals(2) && yhStatus.getNewState0() > 0){
                //TODO 设备开始工作
                this.deviceStartWork(entityMqttDevice,yhStatus);
                this.updateDeviceCommand(deviceHistoryPo.getDeviceNo(),"_run_8A",0);
                log.info("log_3:洗衣机开始工作：设备号：【{}】",deviceHistoryPo.getDeviceNo());
            }

            if(entityMqttDevice.getDeviceStatus().equals(0) && yhStatus.getNewState0().equals(0)){
                //TODO 设备停止工作
                this.deviceStopWork(entityMqttDevice,yhStatus);
                log.info("log_4:洗衣机停止工作：设备号：【{}】",deviceHistoryPo.getDeviceNo());
            }
//            this.updateDeviceInfo(deviceNo, entityMqttDevice.getComId(), entityYhMqtt84.getStatus(),entityYhMqtt84.getErrorStatus(),entityMqttDevice.getOrderStatus(),entityMqttDevice.getSubRun());
        }

        int resultSub = 0;
        if(deviceHistoryPo.getStatus().equals(1)){
            resultSub = 1;
        }else if(Lists.newArrayList(31,34).contains(deviceHistoryPo.getStatus())){
            resultSub=2;
        }else if(Lists.newArrayList(32,35).contains(deviceHistoryPo.getStatus())){
            resultSub=4;
        }else if(deviceHistoryPo.getStatus().equals(33)){
            resultSub=6;
        }
//      一控二变更
        if(Lists.newArrayList(0,1).contains(entityMqttDevice.getOrderStatus())){
            if((yhStatus.getNewSub().equals(1) && yhStatus.getNewState1().equals(0)) || (yhStatus.getNewSub().equals(2) && yhStatus.getNewState2().equals(0))){
//              设备停止工作
                this.deviceStopWork(entityMqttDevice,yhStatus);
                log.info("log_5,吹风机停止工作：设备号：【{}】",deviceHistoryPo.getDeviceNo());
            }
//            this.updateDeviceInfo(deviceNo, entityMqttDevice.getComId(), entityYhMqtt84.getStatus(),entityYhMqtt84.getErrorStatus(),entityMqttDevice.getOrderStatus(),entityMqttDevice.getSubRun());

        }

//        if(deviceHistoryPo.getStatus().equals(30)){
//            this.updateDeviceCommand(deviceHistoryPo.getDeviceNo(),"_run_8A",1);
//        }
//
//        if(deviceHistoryPo.getStatus().equals(33)){
//            this.updateDeviceCommand(deviceHistoryPo.getDeviceNo(),"_run_8A",1);
//        }

        if(Lists.newArrayList(2).contains(entityMqttDevice.getOrderStatus()) || Lists.newArrayList(2).contains(entityMqttDevice.getMqttDeviceType())){
//        （有新订单）
            if(yhStatus.getOrdered().equals(1)){
                if((yhStatus.getNewSub().equals(1) && yhStatus.getNewState1().equals(0)) || (yhStatus.getNewSub().equals(2) && yhStatus.getNewState2().equals(0))){
//              设备停止工作
                    this.deviceStopWork(entityMqttDevice,yhStatus);
                    log.info("log_6,吹风机停止工作：有新订单：设备号：【{}】",deviceHistoryPo.getDeviceNo());
                }
//                this.updateDeviceInfo(deviceNo, entityMqttDevice.getComId(), entityYhMqtt84.getStatus(),entityYhMqtt84.getErrorStatus(),entityMqttDevice.getOrderStatus(),entityMqttDevice.getSubRun());
            }

            if(yhStatus.getOrdered().equals(0)){
                if((yhStatus.getNewSub().equals(1) && yhStatus.getNewState1().equals(0)) || (yhStatus.getNewSub().equals(2) && yhStatus.getNewState2().equals(0))){
                    this.deviceStopWork(entityMqttDevice,yhStatus);
                    log.info("log_7,吹风机停止工作：无新订单或新订单开始：设备号：【{}】",deviceHistoryPo.getDeviceNo());
                }

                //左路开始工作
                if(yhStatus.getNewSub().equals(1) && yhStatus.getNewState1() > 0){
                    this.deviceStartWork(entityMqttDevice, yhStatus);
                    log.info("log_7,吹风机开始工作：左路开始工作：设备号：【{}】",deviceHistoryPo.getDeviceNo());
                    this.updateDeviceCommand(deviceHistoryPo.getDeviceNo(),"_run_8A",1);
                }

                //右路开始工作
                if(yhStatus.getNewSub().equals(2) && yhStatus.getNewState2() > 0){
                    this.deviceStartWork(entityMqttDevice,yhStatus);
                    log.info("log_7,吹风机开始工作：右路开始工作：设备号：【{}】",deviceHistoryPo.getDeviceNo());
                    this.updateDeviceCommand(deviceHistoryPo.getDeviceNo(),"_run_8A",2);
                }
            }
        }
//        Integer resultSub = Integer.valueOf(redisUtil.hmGet("MqttXfDevice:"+ entityMqttDevice.getMqttDeviceNo(),"subRun").toString());
//        if(ObjectUtil.isNotEmpty(resultSub)){
//            entityMqttDevice.setSubRun(resultSub);
//        }

        entityMqttDevice.setSubRun(resultSub);
        if(bUpdate){
            this.updateDeviceInfo(deviceHistoryPo.getDeviceNo(), entityMqttDevice.getComId(), deviceHistoryPo.getStatus(),deviceHistoryPo.getErrorStatus(),yhStatus.getOrdered(),entityMqttDevice.getSubRun());
        }
        log.info("log_7:84结束");
    }

    public static String checkMsg(String msg){
        String body = msg.substring(6, msg.length() - 2);
        String len = msg.substring(2,6);
        String enx = msg.substring(msg.length() - 2);

        String org = DesUtils.Cmd_UnDes(body,DesUtils.datakey);

        String enx1 =DesUtils.xorStr(len+org);
        if(!enx.equals(enx1)){
            throw new RuntimeException(msg+",异或和检测不过");
        }
        return org;
    }

    //平方取反(按位与按位取反2的@newSub次方)
    public static Integer getSubRunB(Integer subRun){
        subRun  = ObjectUtil.isEmpty(subRun)?0:subRun;
        return subRun & (~(int)Math.pow(2,subRun));
    }

    //按位或2的@newSub次方
    public static Integer getSubRunA(Integer subRun){
        subRun  = ObjectUtil.isEmpty(subRun)?0:subRun;
        return subRun | ((int)Math.pow(2,subRun));
    }



    public static void main(String[]  args){
        System.out.println(checkMsg("860013534A283B767C534A283B793AF42A53A150EDE399"));
        System.out.println(checkMsg("860013534A283B767C534A283B7AC3D42887A150EDE30D"));
        System.out.println(checkMsg("860013534A283B767C534A283B79CEBD0478A150EDE39F"));
        System.out.println(checkMsg("860013534A283B767C534A283B7BC383EE64A150EDE3A4"));
        System.out.println(checkMsg("860013534A283B767C534A283B792DD3586EA150EDE334"));
        System.out.println(checkMsg("860013534A283B767C534A283B792DD3586EA150EDE334"));
        System.out.println(checkMsg("87000B534A283B767C534A283B770A"));
        System.out.println(checkMsg("84000D534A283B767C544A283B767C530C"));
        System.out.println(checkMsg("860013534A283B767C534A283B7FC311C48AA1552177C3"));
    }
}
